<?php
// app/Amqp/Consumer/OrderConsumer.php

namespace App\Amqp\Consumer;

use Hyperf\Di\Annotation\Inject;
use App\Model\Order;
use App\Service\EsService;
use Hyperf\Amqp\Result;
use Hyperf\Amqp\Annotation\Consumer;
use Hyperf\Amqp\Message\ConsumerMessage;
use PhpAmqpLib\Message\AMQPMessage;

#[Consumer(exchange: 'order', routingKey: 'order', queue: 'order', name: "OrderConsumer", nums: 1)]
class OrderConsumer extends ConsumerMessage
{
    #[Inject]
    protected EsService $esService;

    public function consumeMessage($data, AMQPMessage $message): Result
    {
        // 获取订单数据
        $order = Order::find($data);
        if (!$order) {   // 订单不存在时的处理
            return Result::DROP;
        }

        try {
            // 添加索引
            $this->esService->create(
                'order_index',      
                'order_'.$order->id,
                $order->toArray()
            );

            //删除索引
            // $this->esService->delete(
            //     'mjs_article',      
            //     'article_'.$data
            // );
        } catch (\RuntimeException $e) {
            // 处理异常，可以选择重试或记录日志
            return Result::REQUEUE;
        }

        return Result::ACK;
    }
}
